/**
 * 动态列表插件
 */

;(
	function($,window,document,undefined){
		var dyTableIndex = 0;
		
		var getRowNum =  function(obj){
			var rows = $(obj).data('rows');
			if(rows){
				$(obj).data('rows',parseInt(rows));
			}else{
				$(obj).data('rows',0);
			}
			return ($(obj).data('rows'));
		};
		var getColumns = function(obj){
			return ($(obj).data('columns'));
		};
		var initEvent =  function(obj){
			//避免事件重复绑定
			$('.dynamicTr').each(function(){
				$(this).unbind( "click" )
			});
			
			$('.dynamicTr').each(function(){
				$(this).click(function(){
					var currentTableId = $(this).parent().parent().parent().attr('id');
					$(document).data("selectedTr_of_"+currentTableId,$(this).attr('indexNum'));//保存当前选中的行号
						
					if (!$(this).hasClass('selectedTr')) { 
						var siblings = $(this).siblings(); 
						$(siblings).each(function(){
							$(this).removeClass("selectedTr");
						});
						$(this).addClass("selectedTr");
					}
				})
				
			}); 
		}
		var addRowNum = function(obj){
			var rows =  getRowNum(obj);
			rows = parseInt(rows)+1;
			$(obj).data('rows',rows);
			initEvent(obj);
			return rows;
		};
		var subRowNum = function(obj){
			var rows =  getRowNum(obj);
			if(rows>0){
				rows = parseInt(rows)-1;
			}
			$(obj).data('rows',rows);
			return rows;
		};
		var addRow = function(domObj,valuesObj){
			var thiz = domObj;
			var columns = $(thiz).data('columns');
			if(!columns)return false;
			//行号处理
			var rowIndex = getRowNum(thiz)+1;
			var currentDyTableIndex =$(thiz).data('dyTableIndex');
			var trNum = (currentDyTableIndex+'_'+rowIndex);
			var newTrHtml = '<tr  indexNum="'+trNum+'"  class="dynamicTr dyTr_'+currentDyTableIndex+'" id="tr_'+trNum+'" >';
			newTrHtml+=('<td>'+rowIndex+'</td>');
			/*
			*{'pojo.name':'dingshuo','pojo.cnName':'丁硕','width':'20','type':'String'}
			*
			*/
			for(var i in columns){
				var name = columns[i]['name'];
				var value = '';
				if(valuesObj && valuesObj[name]){
					value = valuesObj[name];
				}
				var pageType = columns[i]['pageType'];
				if(pageType && pageType=='hidden') {
					newTrHtml+=('<input id="id'+trNum+'"  class="cell_'+trNum+' class_'+name+'" type="hidden" name="'+name+'" value="'+value+'"/>');
					continue;
				}
				
				var readonly = columns[i]['readonly'];
				if(readonly && readonly=='readonly') {
					readonly = ' readonly="readonly" ';
				}else{
					readonly = '';
				}
				
				var disabled = columns[i]['disabled'];
				if(disabled && disabled=='disabled') {
					disabled = ' disabled="disabled" ';
				}else{
					disabled = '';
				}
				
				newTrHtml+=('<td>');
				if(pageType){
					//"number"，"string"，"boolean"，"object"，"function"，"undefined"
					if(pageType=='select'){
						var options = columns[i]['options']
						newTrHtml+=('<select '+readonly+' ' +disabled+' class="cell_'+trNum+' class_'+name+'" name="'+name+'">');
						if(options instanceof Array){
							for(var i in options){
								var selected = '';
								if(options[i][0]==value){
									selected = 'selected';
								}
								newTrHtml+=('<option '+selected+' value="'+options[i][0]+'">'+options[i][1]+'</option>');
							}
						}else{
							 for (var j in options ){
								var selected = '';
								if(j==value){
									selected = 'selected';
								}
								newTrHtml+=('<option '+selected+' value="'+j+'">'+options[j]+'</option>');
							 }
						}
						newTrHtml+=('</select>');
					}else{
						newTrHtml+=('<input '+readonly+' ' +disabled+'  class="cell_'+trNum+' class_'+name+'" type="'+pageType+'" name="'+name+'" value="'+value+'"/>');
					}
					
				}else{//未定义type,默认为input
					newTrHtml+=('<input  '+readonly+' ' +disabled+' class="cell_'+trNum+' class_'+name+'" name="'+name+'" value="'+value+'"/>');
				}
				newTrHtml+=('</td>');
			}
			newTrHtml+='</tr>';
			/*
			* 插入标题后
			*/
			var theadId = 'thread'+$(thiz).data('dyTableIndex');
			$("#"+theadId).after(newTrHtml);
			addRowNum(thiz);
		}
		
		
		var methods = {
			init : function(obj){
				if(!$(this).data('dyTableIndex')){//未保存有dyTableIndex,说明未进行初始化
					dyTableIndex +=1;
					$(this).data('dyTableIndex',dyTableIndex);
					$(this).data('dyTableId',$(this).attr('id'));//保存div的id
					var columns = obj.columns;
					$(this).data('columns',columns);//存储columns 供addRow()使用
					
					var HTML =  '<div  class="scroll_layer"  align="center" style="width: 98%">'+
								'<table  class="dynamicTable" cellspacing="0px" style="width: 100% ;height: auto;table-layout: fixed">'+
									'<thead id="thread'+dyTableIndex+'"><tr>'+
								 	'<td width="3%">序号</td>';
				 	for(var i in columns){
				 		var pageType = columns[i]['pageType'];
				 		if(pageType && pageType=='hidden') continue;
				 		var width = columns[i]['width'];
				 		if(width)
					 		HTML+=('<td width="'+columns[i]['width']+'">'+columns[i]['cnName']+'</td>');
				 		else
					 		HTML+=('<td>'+columns[i]['cnName']+'</td>');
					 		
					}
				 	HTML+='</tr></thead></table></div>';
				 	
				 	
				 	//初始化表头
					$(this).append(HTML);
					
					//根据url初始化 具体数据
					var thiz = this;
					if(obj.url){
						$(this).data('url',obj.url);
						 $.post(obj.url,
							  function(data,status){
							 	var dataObj = eval('('+data+')')
							 	for(var q in dataObj){
							 		addRow(thiz,dataObj[q]);
							 	}
					 		  }
						 );
				 	}
					
				}
			},
			reload:function(){
				$(this).data('rows',0);
				//delall
				var dyTableIndex = $(this).data('dyTableIndex');
				
				$('.dyTr_'+dyTableIndex).each(function(){
					$(this).remove();
				});
				
				//
				var url = $(this).data('url');
				var thiz = this;
				if(url){
					$(this).data('url',url);
					 $.post(url,
						  function(data,status){
						 	var dataObj = eval('('+data+')')
						 	for(var q in dataObj){
						 		addRow(thiz,dataObj[q]);
						 	}
				 		  }
					 );
			 	}
			},
			getSelected:function(){
				var selectedTrIndex =  $(document).data("selectedTr_of_"+$(this).data('dyTableId'));
				if(selectedTrIndex){
					var selectedRow = {};
					$('.cell_'+selectedTrIndex).each(function(){
						var attr = $(this).attr('name');
						selectedRow[attr+''] = $(this).val();
					})
					return selectedRow;
				}else{
					
					return false;
				}
			},
			getAll:function(prefix){
				var dyTableIndex = $(this).data('dyTableIndex');
				
				var allRows =[]; 
				var attrPrefix = '';
				if(prefix) attrPrefix = prefix+'.';
				$('.dyTr_'+dyTableIndex).each(function(){
					var trIndexNum = ($(this).attr('indexNum'));
					var selectedRow = {};
					$('.cell_'+trIndexNum).each(function(){
						var name = $(this).attr('name');
						var disabled = $(this).attr('disabled');
						if(!disabled){
							selectedRow[attrPrefix+''+name] = $(this).val();
						}
					})
					selectedRow['trNum'] = trIndexNum;
					allRows.push(selectedRow);
				});
				
				return allRows;
			},
			addRow:function(valuesObj){
				addRow(this,valuesObj);
			},
			addSubRow : function(){
			},
			delRow : function(func){
				var currentIndex =  $(document).data("selectedTr_of_"+$(this).data('dyTableId'));
				$('#tr_'+currentIndex).remove();
			},
			delAll : function(){
				alert('delAll');
			}
	};
	
	/*
	* 在插件中使用dynamicTable
	*/
	$.fn.dynamicTable = function(method) {
		if(methods[method]){
			return methods[method].apply(this,Array.prototype.slice.call(arguments,1));
		}else if(typeof method==='object'||!method){
			return methods.init.apply(this,arguments);
		}else{
			$.error('Method'+method+' does not exists in the dynamicTable!');
		}
    }
	
})(jQuery,window,document)
